<?php
namespace app\controllers;

use app\models\Mobile;
use app\models\MobileBorrow;
use mvc\helpers\Tool;
use mvc\web\Controller;
use mvc\web\Pagination;

class MobileController extends Controller
{
    public function actionIndex()
    {
        $model = new Mobile();

        $page = isset($_GET['page']) ? $_GET['page'] : 1;
        $pagination = new Pagination($model->count(), $page);

        $data = $model
            ->limit("$pagination->offset,$pagination->limit")
            ->all();

        $model2 = new MobileBorrow();
        foreach ($data as $key => &$item) {
            $cloneModel2 = clone $model2;
            $one = $cloneModel2->where("mobile_id=$item[id] and status=0")->one();
            if($one) {
                $item['borrow_user'] = $one['borrow_user'];
                $item['borrow_time'] = $one['borrow_time'];
                $item['should_return_time'] = $one['should_return_time'];
            } else {
                $item['borrow_user'] = '暂无';
                $item['borrow_time'] = '暂无';
                $item['should_return_time'] = '暂无';
            }
        }

        return $this->render('index', [
            'pagination' => $pagination,
            'data' => $data,
        ]);
    }

    public function actionCreate()
    {
        if (Tool::isAjax()) {
            $data = $_POST;
            $model = new Mobile();
            if ($model->insert($data)) {
                $this->jsonResponse(['status' => 1]);
            } else {
                $this->jsonResponse(['status' => 0, 'msg' => $model->getHeadError()]);
            }
        }
        
        return $this->render('create', [

        ]);
    }
}